<?php
namespace app\index\controller;

use app\index\model\UserModel;
use app\index\model\RoomModel;
use GatewayClient\Gateway;

use think\Controller;
use app\common\RedisDB;
use think\Request;
use app\index\model\Roomlog;

class Index extends Controller
{

    protected function _initialize()
    {
        header("Access-Control-Allow-Origin: *");
    }

    public function showfeed()
    {
        print_r(db('user')->select());
    }

    public function wtimerset($value)
    {
        $client = stream_socket_client("tcp://10.45.178.246:7274");
        if(!$client)exit("can not connect");
        print_r('1'.fwrite($client, '{"type":"add","roomid":"123","time":"'.$value.'","content":"index/wtimerset/value/10", "user":"admin", "pass":"******"}'."\n").'2');
    }

    public function wtimerdel()
    {
        $client = stream_socket_client("tcp://10.45.178.246:7274");
        if(!$client)exit("can not connect");
        fwrite($client, '{"type":"del","roomid":"123","content":"index/wtimerset/value/10", "user":"admin", "pass":"******"}'."\n");
    }

    public function addlog()
    {
        $info['id']=123456;
        $info['sid']=1;
        $data['roomsid']=$info["sid"];
        $data['roomid']=$info['id'];
        $data['msg']='测试数据';
        $data['info'] = json_encode($info);
        $data['time']=date("Y-m-d H:i:d",time());
        $data['url']= Request::instance()->url(true);
        (new Roomlog())->insert($data);
        print_r((new Roomlog())->select());
    }


    public function testwork()
    {
        $r = (db('rechangeconfig')->select());
        foreach($r as $k=>$v) {
            if ($v['money'] == 50)
                $v['diamond'] = 500;
            else if ($v['money'] == 100)
                $v['diamond'] = 1000;
            db('rechangeconfig')->update($v);
        }
    }

    public function testwork1()
    {
        $redis = RedisDB::factory('pss');
        print_r($redis->hGet("xx",'123'));//,4356452);
    }

//    public function index()
//    {
//        $appid='wx09b792ef7b08906e';
//
//        $redirect_uri = urlencode ( 'http://ms.redli366.com/api.php/index/index/senduserinfo' );
//        header("location:https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_userinfo&state=123&connect_redirect=1#wechat_redirect");
//    }

    public function senduserinfo2()
    {
        $code = $_GET['code'];
        $state = $_GET['state'];
//换成自己的接口信息
        $appid = config("wxconfig.appid");
        $appsecret = config("wxconfig.appsecret");
        if (empty($code)) $this->error('授权失败');
        $token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code';
        $token = json_decode(file_get_contents($token_url));
        if (isset($token->errcode)) {
            echo '<h1>错误：</h1>'.$token->errcode;
            echo '<br/><h2>错误信息：</h2>'.$token->errmsg;
            exit;
        }
        $access_token_url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid='.$appid.'&grant_type=refresh_token&refresh_token='.$token->refresh_token;
//转成对象
        $access_token = json_decode(file_get_contents($access_token_url));
        if (isset($access_token->errcode)) {
            echo '<h1>错误：</h1>'.$access_token->errcode;
            echo '<br/><h2>错误信息：</h2>'.$access_token->errmsg;
            exit;
        }
        $user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token->access_token.'&openid='.$access_token->openid.'&lang=zh_CN';
//转成对象
        $user_info = json_decode(file_get_contents($user_info_url));
        if (isset($user_info->errcode)) {
            echo '<h1>错误：</h1>'.$user_info->errcode;
            echo '<br/><h2>错误信息：</h2>'.$user_info->errmsg;
            exit;
        }

        $user_info =  json_decode(json_encode($user_info),true);//返回的json数组转换成array数组

//打印用户信息
        echo '<pre>';
        print_r($user_info['openid']);
        echo '</pre>';



        $type = 0;

        $user = db('user')->where("openid='{$user_info['openid']}'")->find();

        if ($user == null) {
            foreach ($user_info as $key => $value) {
                if ($key != 'privilege')
                    $data[$key] = $value;
            }
            $data['nickname'] = $this->emoji_encode($user_info['nickname']);
            $data['diamond'] = 200;
            $data['createtime'] = date("Y-m-d H:i:s", time());
            $data['lastlogintime'] = date("Y-m-d H:i:s", time());
            $data['createtype'] = $type;
            try {
                db("user")->insert($data);
            } catch (PDOException $e) {
                print "错误: " . $e->getMessage() . "<br />";
                print "行号: " . $e->getLine() . "<br />";
                die();
            }

        } else {
            if ($user['status'] == 0) {
                //禁止登陆账号
            } else if ($user['unusedtime'] > date("Y-m-d H:i:s", time())) {
                //小黑屋账号
            }

            $user['lastlogintime'] = date("Y-m-d H:i:s", time());

            foreach ($user_info as $key => $value) {
                if ($key != 'privilege')
                    $user[$key] = $value;
            }
            $user['nickname'] = $this->emoji_encode($user_info['nickname']);
            try {
                db("user")->update($user);
            } catch (PDOException $e) {
                print "错误: " . $e->getMessage() . "<br />";
                print "行号: " . $e->getLine() . "<br />";
                die();
            }
        }


        $user = db("user")->where("openid='{$user_info['openid']}'")->find();
        $uid = $user['openid'];
        //session('uid',$uid);


        $mUser = new UserModel($user_info['openid'], false);
        $token = md5(date('YmdHis') . mt_rand(1000, 9999) . $uid);
        $redis = RedisDB::factory('auth');
        $redis->hSet('auth', $uid, $token);
//        if(!$mUser->login($user['openid'], $token)){
//            $this->error('InvalidToken');
//            return ;
//        }
        $mUser->save($user);
        $mUser->printinfo();

        $mUser = new UserModel(null, false);
        if (!$mUser->login($uid, $token, '127.0.0.1')) {
            $this->error('InvalidToken');
            return;
        }
        $user = $mUser->getInfo();
        print_r($user);

        //write auth info
        $token = md5(date('YmdHis') . mt_rand(1000, 9999) . $uid);
        $redis->hSet('auth', $uid, $token);


        //ret
        $result = array(
            'code' => 4,
            'auth' => true,
            'uid' => $uid,
            'token' => $token,
        );
        echo json_encode($result);
    }

    public function senduserinfo()
    {
//        $result = array("auth"=>true,"uid"=>"oibzjw4L_q2FGufK6hNBjTc82i-w","token">"sss");
//        return json_encode($result);

        $code = $_GET['code'];
        $state = $_GET['state'];
        // $type = $_GET['type'];
        if(isset($_GET['type']))
            $type=$_GET['type'];
        else
            $type = 0;
//换成自己的接口信息
        $appid = config("wxconfig.appid");
        $appsecret = config("wxconfig.appsecret");

        if (empty($code)) {
            $result = array(
                'uid' => 'error',
                'auth' => '授权失败',

                'token' => 5345325,
            );
            echo json_encode($result);
            return;
        }
        $token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . '&secret=' . $appsecret . '&code=' . $code . '&grant_type=authorization_code';
        $token = json_decode(file_get_contents($token_url));
        if (isset($token->errcode)) {
            $result = array(
                'token' => 1,
                'uid' => $token->errcode,
                'auth' => $token->errmsg,
            );
            echo json_encode($result);
            return;
        }
        $access_token_url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=' . $appid . '&grant_type=refresh_token&refresh_token=' . $token->refresh_token;
//转成对象
        $access_token = json_decode(file_get_contents($access_token_url));
        if (isset($access_token->errcode)) {
            $result = array(
                'token' => 2,
                'uid' => $access_token->errcode,
                'auth' => $access_token->errmsg,
            );
            echo json_encode($result);
            return;
        }
        $user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token->access_token . '&openid=' . $access_token->openid . '&lang=zh_CN';
//转成对象
        $user_info = json_decode(file_get_contents($user_info_url));
        if (isset($user_info->errcode)) {
            $result = array(
                'token' => 3,
                'uid' => $user_info->errcode,
                'auth' => $user_info->errmsg,
            );
            echo json_encode($result);
            return;
        }

        $user = db('user')->where("openid='{$user_info->openid}'")->find();

        if ($user == null) {
            foreach ($user_info as $key => $value) {
                if ($key != 'privilege')
                    $data[$key] = $value;
            }
            $data['nickname'] = $this->emoji_encode($user_info->nickname);
            $data['diamond'] = 200;
            $data['createtime'] = date("Y-m-d H:i:s", time());
            $data['lastlogintime'] = date("Y-m-d H:i:s", time());
            $data['createtype'] = $type;
            try {
                db("user")->insert($data);
            } catch (PDOException $e) {
                print "错误: " . $e->getMessage() . "<br />";
                print "行号: " . $e->getLine() . "<br />";
                die();
            }

        } else {
            if ($user['status'] == 0) {
                //禁止登陆账号
            } else if ($user['unusedtime'] > date("Y-m-d H:i:s", time())) {
                //小黑屋账号
            }

            $user['lastlogintime'] = date("Y-m-d H:i:s", time());

            foreach ($user_info as $key => $value) {
                if ($key != 'privilege')
                    $user[$key] = $value;
            }
            $user['nickname'] = $this->emoji_encode($user_info->nickname);
            try {
                db("user")->update($user);
            } catch (PDOException $e) {
                print "错误: " . $e->getMessage() . "<br />";
                print "行号: " . $e->getLine() . "<br />";
                die();
            }
        }


        $user = db("user")->where("openid='{$user_info->openid}'")->find();
        $uid = $user['openid'];
        //session('uid',$uid);

        $mUser = new UserModel($user_info->openid, false);
        $token = md5(date('YmdHis') . mt_rand(1000, 9999) . $uid);
        $redis = RedisDB::factory('auth');
        $redis->hSet('auth', $uid, $token);
//        if(!$mUser->login($user['openid'], $token)){
//            $this->error('InvalidToken');
//            return ;
//        }
        $mUser->save($user);

        //write auth info
        $token = md5(date('YmdHis') . mt_rand(1000, 9999) . $uid);
        $redis->hSet('auth', $uid, $token);


        //ret
        $result = array(
            'code' => 4,
            'auth' => true,
            'uid' => $uid,
            'token' => $token,
        );
        echo json_encode($result);
    }

    private function emoji_encode($nickname)
    {
        $strEncode = '';
        $length = mb_strlen($nickname, 'utf-8');
        for ($i = 0; $i < $length; $i++) {
            $_tmpStr = mb_substr($nickname, $i, 1, 'utf-8');
            if (strlen($_tmpStr) >= 4) {
                $strEncode .= '';//[[EMOJI:'.rawurlencode($_tmpStr).']]';
            } else {
                $strEncode .= $_tmpStr;
            }
        }
        return $strEncode;
    }

    public function posttest()
    {
        $request = \think\Request::instance();
        echo date("Y-m-d H:i:s",time()).'url with domain: ' . $request->url(true) . '<br/>';
    }

    public function logintest()
    {
        $appid = 'wxfddcd87daadba25e';

//scope=snsapi_base 实例
        $redirect_uri = urlencode ( 'http://g.idiange.cn/api.php/index/index/senduserinfo2' );
        $url ="https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_base&state=1#wechat_redirect";
        header("Location:".$url);

    }

    public function inituser($uid)
    {
        /*$appid = APP_ID;
        $redirect_url = urlencode('http://www.xx.com/callback.php');
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appid}&redirect_uri={$redirect_url}&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect";
        $data = array(
        'auth' => false,
        'url' => $url,
    );*/
//        $uid='oibzjw4L_q2FGufK6hNBjTc82i-y';
        $user = DB('user')->where("openid", $uid)->find();
        $mUser = new UserModel($uid, true, $user);
        $mUser->save($user);
        //write auth info
        $token = md5(date('YmdHis') . mt_rand(1000, 9999) . $uid);
        RedisDB::factory("auth")->hSet('auth', $uid, $token);

        //ret
        $result = array(
            'code' => 4,
            'auth' => true,
            'uid' => $uid,
            'token' => $token,
        );
        echo json_encode($result);
        return;


//        $appid='wxf449461c025a9f86';
//        $redirect_uri = urlencode ( 'http://ms.redli366.com/api.php/index/index/senduserinfo' );
//        header("location:https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_userinfo&state=123&connect_redirect=1#wechat_redirect");
    }

    function object2array(&$object)
    {
        $object = json_decode(json_encode($object), true);
        return $object;
    }

    function request_post($url = '', $param = '')
    {
        if (empty($url) || empty($param)) {
            return false;
        }

        $postUrl = $url;
        $curlPost = $param;
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_URL, $postUrl);//抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($ch);//运行curl
        curl_close($ch);

        return $data;
    }

    public function post2()
    {//file_get_content

        $url = "http://www.yihu.com//DoctorArrange/doGetAllRegListBySnsSearch";
        $post_data = 'sns%5B0%5D%5Bsn%5D=23716&sns%5B0%5D%5Bhid%5D=1255&sns%5B1%5D%5Bsn%5D=343975&sns%5B1%5D%5Bhid%5D=21476&sns%5B2%5D%5Bsn%5D=344412&sns%5B2%5D%5Bhid%5D=21226&sns%5B3%5D%5Bsn%5D=343722&sns%5B3%5D%5Bhid%5D=21440&sns%5B4%5D%5Bsn%5D=357866&sns%5B4%5D%5Bhid%5D=20280&sns%5B5%5D%5Bsn%5D=356986&sns%5B5%5D%5Bhid%5D=20233&sns%5B6%5D%5Bsn%5D=362554&sns%5B6%5D%5Bhid%5D=21186&sns%5B7%5D%5Bsn%5D=362720&sns%5B7%5D%5Bhid%5D=21323&sns%5B8%5D%5Bsn%5D=387060&sns%5B8%5D%5Bhid%5D=21813&sns%5B9%5D%5Bsn%5D=410572&sns%5B9%5D%5Bhid%5D=1003210';
        $res = $this->request_post($url, $post_data);
        print_r($res);
    }

    public function deluser()
    {
//       $where['nickname']='楚健';
//        $user = db('user')->where($where)->find();
//        db('user')->delete($user);
//
//        $where['nickname']='晨晨';
//        $user = db('user')->where($where)->find();
//        db('user')->delete($user);
        $user = db('user')->select();
        print_r($user);

    }

    public function offline($cid, $ip)
    {
        Gateway::$registerAddress = GATEWAYADDRESS;

        Gateway::sendToAll(json_encode(array('type' => 'logout', 'data' => array('cid' => $cid, 'ip' => $ip))));

        $redis = RedisDB::factory('session');
        $uid = $redis->get($cid);
        $mUser = new UserModel($uid);
        $ret = Gateway::unbindUid($cid, $uid);
        //玩家离线处理
        if ($ret) {
            $user = $mUser->getInfo();
            if (!empty($user['roomid'])) {
                $mRoom = new RoomModel($mUser, $user['roomid']);
                $mRoom->offline($cid, $user['seatid']);
            }
        }
    }

    public function getid()
    {
        $user = db('user')->where("openid='oZiF30oaNofn8i0YyBtburdcYBDs'")->find();

        $mUser = new UserModel(null, false);
        $mUser->save($user);
        print_r($mUser->getInfo());
    }

    public function create($client_id, $uid, $round, $type, $jcard, $multiples)
    {
        $mUser = new UserModel($uid);
        $user = $mUser->getInfo();
        $diamond = config("roomdiamond.{$round}");
        if ($user['diamond'] < $diamond) {
            $json = array('type' => 'Error', 'data' => 'GoldLess');
            Gateway::$registerAddress = GATEWAYADDRESS;
            Gateway::sendToUid($uid, json_encode($json));
            return;
        }

        if (!empty($user['roomid']) && $user['roomid'] != '0') {
            $json = array('type' => 'Error', 'data' => 'InRoom');
            Gateway::$registerAddress = GATEWAYADDRESS;
            Gateway::sendToUid($uid, json_encode($json));
            return;
        }

        $mGame = new RoomModel($mUser);
        $ret = $mGame->create($round, $type, $jcard, $multiples);
        if (!$ret) {
            $json = array('type' => 'Error', 'data' => 'CreateFailed');
            Gateway::$registerAddress = GATEWAYADDRESS;
            Gateway::sendToUid($uid, json_encode($json));
            return;
        }

        //update user info
//        $mUser->save(array(
//            'roomid' => $mGame->getId(),
//        ));

        Gateway::$registerAddress = GATEWAYADDRESS;
        Gateway::joinGroup($client_id, "game-{$ret['roomid']}");
        $json = array("type" => "Index.create", 'data' => $ret);
        Gateway::sendToUid($uid, json_encode($json));
    }

    public function btnclick($uid,$btnid)
    {
        $r = db('buttonclick')->where("buttonid='{$btnid}' and uid='{$uid}'")->find();
        if($r) {
            $data['clicktimes'] = $r['clicktimes']+1;
            db('buttonclick')->where("buttonid='{$btnid}' and uid='{$uid}'")->update($data);
        }
        else{
            $data['uid'] = $uid;
            $data['buttonid'] = $btnid;
            $data['clicktimes'] = 1;
            db('buttonclick')->insert($data);
        }
    }

    public function join($uid, $roomid)
    {
        Gateway::$registerAddress = GATEWAYADDRESS;

        if (!$roomid) {
            $json = array("err" => "201", 'data' => 'InvalidRoomId');
            Gateway::sendToUid($uid, json_encode($json));
            return;
        }
        $redis = RedisDB::factory('game');
        if (!$redis->exists("room:{$roomid}")) {
            $json = array("err" => "201", 'data' => 'RoomNotFound');
            Gateway::sendToUid($uid, json_encode($json));
            return;
        }

        $mUser = new UserModel($uid);
        $user = $mUser->getInfo();

        if (!empty($user['roomid']) && $user['roomid'] != '0') {
            $json = array("err" => "201", 'data' => 'InRoom');
            Gateway::sendToUid($uid, json_encode($json));

            return;
        }
        $mGame = new RoomModel($mUser, $roomid);
        $ret = $mGame->join($user['openid']);
        if (!$ret) {
            $json = array("err" => "201", 'data' => 'PositionLess');
            Gateway::sendToUid($uid, json_encode($json));
            return;
        }
        $json = array("type" => "Index.join", 'data' => $ret);
        Gateway::sendToUid($uid, json_encode($json));
    }

    public function bind($uid, $client_id, $token, $ip = '')
    {
        Gateway::$registerAddress = GATEWAYADDRESS;

        $mUser = new UserModel(null, false);
        if (!$mUser->login($uid, $token, $ip)) {
            $this->error('InvalidToken');
            return;
        }
        $redis = RedisDB::factory('session');
        $redis->set($client_id, $uid);
        $cids = Gateway::getClientIdByUid($uid);
        if (count($cids) > 0) {
            foreach ($cids as $k => $v)
                Gateway::unbindUid($v, $uid);
        }
        Gateway::bindUid($client_id, $uid);
        //Gateway::joinGroup($client_id,"game-001");
        //获取数据
        $user = $mUser->getInfo();
        print_r($user);

        $data = array('user' => $user, 'uid' => $uid);
        $json = array("type" => "login", 'data' => $data);
        Gateway::sendToUid($uid, json_encode($json));
    }

//    public function loginByWX()
//    {
//        $this->loginCallback();
////        $state  = md5(uniqid(rand(), TRUE));
////        $_SESSION["wx_state"]    =   $state; //存到SESSION
////        $callback = urlencode("http://www.niuyouplus.com/index.php/index/login/LoginCallback");
////        $appid=config('wx.appid');
////
////        $wxurl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$callback&response_type=code&scope=snsapi_userinfo&state=$state&connect_redirect=1#wechat_redirect";
////        header("Location: $wxurl");
//    }

//    /**
//     * 微信登录回调函数
//     */
//    public function loginCallback()
//    {
//        if ($_GET['state'] != $_SESSION["wx_state"]) {
//            $data=array("code"=>5001,"info"=>'');
//            return json(array("type"=>"error","data"=>$data));
//        }
//        $appid = config('wx.appid');
//        $appsecret = config('wx.appsecret');
//        $token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . '&secret=' . $appsecret . '&code=' . $_GET['code'] . '&grant_type=authorization_code';
//        $token = json_decode(file_get_contents($token_url));
//        if (isset($token->errcode)) {
//            $data=array("code"=>$token->errcode,"info"=> $token->errmsg);
//            return json(array("type"=>"error","data"=>$data));
//        }
//        $access_token_url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=' . $appid . '&grant_type=refresh_token&refresh_token=' . $token->refresh_token;
////转成对象
//        $access_token = json_decode(file_get_contents($access_token_url));
//        if (isset($access_token->errcode)) {
//            $data=array("code"=>$access_token->errcode,"info"=> $access_token->errmsg);
//            return json(array("type"=>"error","data"=>$data));
//        }
//        $user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token->access_token . '&openid=' . $access_token->openid . '&lang=zh_CN';
////转成对象
//        $user_info = json_decode(file_get_contents($user_info_url));
//        if (isset($user_info->errcode)) {
//            $data=array("code"=>$user_info->errcode,"info"=> $user_info->errmsg);
//            return json(array("type"=>"error","data"=>$data));
//        }
//        //保存数据
//        $user = db('user')->where('openid', $user_info->openid)->find();
//
//        if ($user == null) {
//            $data =  json_decode( json_encode( $user_info),true);
//            $data['privilege']=json_encode($data['privilege']);
//            $data['createtime']=date("Y-m-d H:i:s", time());
//            $data['lastlogintime']=date("Y-m-d H:i:s", time());
//            db("user")->insert($data);
//        } else {
//
//            if ($user['status'] == 0) {
//                //禁止登陆账号
//            } else if ($user['unusedtime'] > date("Y-m-d H:i:s", time())) {
//                //小黑屋账号
//            }
//            $user['lastlogintime'] = date("Y-m-d H:i:s", time());
//            foreach ($user_info as $key => $value) {
//                $user[$key] = $value;
//            }
//            $user['privilege']=json_encode($user['privilege']);
//            db("user")->update($user);
//        }
//
//        $user=db("user")->where("openid='oibzjw4L_q2FGufK6hNBjTc82i-w'")->find();
//        $uid=$user['openid'];
//        session('uid',$uid);
//
//        $mUser = new UserModel(null, false);
//
//        $token = md5(date('YmdHis') . mt_rand(1000, 9999) . $uid);
//        $redis=RedisDB::factory('auth');
//        $redis->hSet('auth', $uid, $token);
//        if(!$mUser->login($user['openid'], $token)){
//            $this->error('InvalidToken');
//            return ;
//        }
//
//        $redis->hMSet("user:$uid", $user);
//
//        //write auth info
//        $token = md5(date('YmdHis') . mt_rand(1000, 9999) . $uid);
//        $redis->hSet('auth', $uid, $token);
//
//        //setcookie
//        setcookie('three_user', $uid, time() + 86400);
//        setcookie('three_token', $token, time() + 86400);
//
//        //ret
//        $result = array(
//            'auth' => true,
//            'uid' => $uid,
//            'token' => $token,
//        );
//        echo json_encode($result);
//
//    }

    function getRecords($uid)
    {
        $where = '';
        for ($i = 1; $i <= 8; ++$i) {
            $where .= "openid$i" . "='$uid' or ";
        }
        $where = substr($where, 0, strlen($where) - 3);
        $list = db('records')->where($where)->order('id', 'desc')->select();
        Gateway::$registerAddress = GATEWAYADDRESS;
        $json = array("type" => "Records.info", 'data' => $list);
        Gateway::sendToUid($uid, json_encode($json));
    }
    
    
}

